#include <boost/filesystem.hpp>
#include <iostream>
#include <fstream>
#include "XFile.h"

using namespace std;

static const int SIZE_FILE_MAX = 1024 * 1024 * 10;

XFile::XFile(void)
{
  m_fileConetnt = new char[SIZE_FILE_MAX];
  memset((void*)m_fileConetnt, 0x00, SIZE_FILE_MAX);
}

XFile::~XFile(void)
{
  if(m_fileConetnt != NULL)
  {
    delete[] m_fileConetnt;
    m_fileConetnt = NULL;
  }
}

void XFile::checkDir(const string& dirPath)
{
  string tmp;
 unsigned  int index=0;
  int pos = 1;
  //index =dirPath.find("\\",pos);//win
  index =dirPath.find("/",pos);
  while (index != string::npos)
  {
    tmp = dirPath.substr(0,index);
    pos = index+1;
    if(!boost::filesystem::is_directory(tmp))
    {
      boost::filesystem::create_directory(tmp);
    }
    //index = dirPath.find("\\",pos);
    index = dirPath.find("/",pos);
  }
  if(!boost::filesystem::is_directory(dirPath))
  {
    boost::filesystem::create_directory(dirPath);
  }
}

bool XFile::isExists(const char *filePath)
{
  return boost::filesystem::exists(filePath);
}

bool XFile::writeFile(const string& content, const string& filePath)
{
 fstream file;
 file.open(filePath.c_str(),ios::in|ios::out|ios::app);
 if(!file.is_open())
 {
   return false;
 }
 file.write(content.c_str(), content.length());
 file.close();
 return true;
}

void XFile::writeBinary(const char* content ,const int len, const char* path)
{
  fstream file;
  file.open(path,ios_base::in|ios_base::out|ios_base::app|ios::binary);
  if(!file.is_open())
  {
    throw("[XFile::writeBinary]File open faild!");
  }
  file.write(content, len);
  file.close();
}

void XFile::deleteFile(const char* filePath)
{
  boost::filesystem::remove(filePath);
}
bool XFile::writeFile(const char* msg,const int len, const char* filePath)
{
  fstream file;
  file.open(filePath,ios::in|ios::out|ios::app);//|ios::app);
  if(!file.is_open())
  {
    return false;
  }
  file.write(msg, len);
  file.close();
  return true;
}

void XFile::readFile(const string& filePath, string& content)
{
  memset((void*)m_fileConetnt, 0x00 , SIZE_FILE_MAX);
  std::ifstream file(filePath.c_str(), std::ios_base::in|std::ios_base::ate|std::ios_base::binary);
  long file_length = file.tellg();
  file.seekg(0, std::ios_base::beg);
  file.clear();
  file.read(m_fileConetnt, file_length);
  file.close();
  string strTemp(m_fileConetnt, 0, file_length);
  content.assign(strTemp);
}

bool XFile::readFile(char* msg, int &len, const char* filePath)
{
  ifstream file;
  file.open(filePath,ios::in|ios::out|ios::binary);
  if(!file.is_open())
  {
    return false;
  }
  file.seekg(0, ios::end);
  len = file.tellg();
  file.seekg(0,ios::beg);
  file.read(msg, len);
  file.close();
  return true;
}